package com.lovedice.util;

import com.lovedice.LoveDice;

import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.preference.PreferenceManager;

public class AccelerometerReader {

    private SensorManager theSensorManager;
    private boolean theRegisteredSensor;
    private boolean theAcceleratorSensorAvailable;
    private boolean theAcceleratorSensorPreferenceEnabled;
    private Sensor theAccelerometerSensor;
    private float theSensibilityValue;

    public AccelerometerReader(SensorManager SensorService) {
        theSensorManager = SensorService;
        theRegisteredSensor = false;
        theAcceleratorSensorAvailable = false;
        theSensibilityValue = 14.0F;
        
        for (Sensor sensor : theSensorManager.getSensorList(Sensor.TYPE_ALL)) {
			if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
				theAccelerometerSensor = sensor;
				theAcceleratorSensorAvailable = true;
			}
		}
        
	}
    
    public void register(LoveDice loveDice) {
    	getPreferences(loveDice);
    	if (theAcceleratorSensorAvailable && theAcceleratorSensorPreferenceEnabled ) {
    		theSensorManager.registerListener(loveDice, theAccelerometerSensor, SensorManager.SENSOR_DELAY_FASTEST);
    		theRegisteredSensor = true;
    	}
    }
    
	public void unregister(LoveDice loveGame) {
        if (theRegisteredSensor) {
            theSensorManager.unregisterListener(loveGame);
            theRegisteredSensor = false;
        }
	}
	
	public String readSensor(SensorEvent sensorEvent){
		StringBuffer StringBuff = new StringBuffer();
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
            StringBuff.append("X-axis:").append(sensorEvent.values[0]).append("\n");
            StringBuff.append("Y-axis:").append(sensorEvent.values[1]).append("\n");
            StringBuff.append("Z-axis:").append(sensorEvent.values[2]);
        }
        System.out.println(theSensibilityValue);
        return StringBuff.toString();
	}

	public boolean isShaking(SensorEvent sensorEvent){
        return (sensorEvent.values[0] > theSensibilityValue || sensorEvent.values[0] < (theSensibilityValue-(theSensibilityValue*2)));
	}
	
    private void getPreferences(LoveDice loveDice) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(loveDice);
        theSensibilityValue = Float.parseFloat(prefs.getString("listSensibility", "14"));
        theAcceleratorSensorPreferenceEnabled = prefs.getBoolean("enableMovement", true);
    }
}
